<?php 
//all the class/function includes are managed in the includer file
include("include/includer.php");
//include the rss feed parser
require_once('magpierss72/rss_fetch.inc');

//get all the configuration variables (custom function in newzbook.php include)
getConfigVars();  

//Get all the URL parameters (_GET)
if(isset($_GET['action'])) {
  $action = $_GET['action'];
}
if(isset($_GET['category'])) {
	$category = $_GET['category'];
}
if(isset($_GET['path'])) {
	$path = $_GET['path'];
}
if(isset($_GET['showid'])) {
	$showid = $_GET['showid'];
}
if(isset($_GET['season'])) {
	$season = $_GET['season'];
}
if(isset($_GET['command'])) {
	$command = $_GET['command'];
}
if(isset($_GET['artistid'])) {
	$artistid = $_GET['artistid'];
}
if(isset($_GET['albumid'])) {
	$albumid = $_GET['albumid'];
}


//setup some URL variables that we will use
$XBMC_host = "xbmclive";
$XBMC_port = "2222";
$XBMC_username = "xbmc";
$XBMC_password = "xbmc";
$XBMC_commandURL = "http://$XBMC_username:$XBMC_password@$XBMC_host:$XBMC_port/xbmcCmds/xbmcHttp?command="
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<HEAD>
    <?php standardHead("XBMC Media Player"); ?>
	<link type="text/css" href="style/smoothness/jquery-ui-1.7.2.custom.css" rel="stylesheet" />	
	<script type="text/javascript" src="js/jquery-1.3.2.min.js"></script>
	<script type="text/javascript" src="js/jquery-ui-1.7.2.custom.min.js"></script>
	<style>
		.ui-tabs .ui-tabs-panel {
			padding:0px;
		}
		.ui-tabs .ui-tabs-nav li a {
			padding:0.5em 0.15em;
			font-size:0.75em;
		}
		/*
		#tabs { height: 300px; } 
		.tabs-bottom { position: relative; } 
		.tabs-bottom .ui-tabs-panel { height: 260px; overflow: auto; } 
		.tabs-bottom .ui-tabs-nav { position: absolute !important; left: 0; bottom: 0; right:0; padding: 0 0.2em 0.2em 0; } 
		.tabs-bottom .ui-tabs-nav li { margin-top: -2px !important; margin-bottom: 1px !important; border-top: none; border-bottom-width: 1px; }
		.ui-tabs-selected { margin-top: -3px !important; }
		*/
		#np_controls a {
			border:1px solid #888;
			-webkit-border-radius:5px;
			padding:0px 10px 2px;
			margin-right:3px;
		}
	</style>
</HEAD>

<BODY>
<?php internetSecurity(); ?>
<div style="visibility:hidden;display:none;" id="progress"><div id="progress_bg"></div><a name="loading" /><div id="progress_box"><img id="progress_image" style="padding-left:5px;padding-top:5px;" src="images/ajax-loader.gif" alt="loading...">Your request is being processed...</div></div>
<div class="headercontent">
  <?php headerContent(); ?>
</div>
<div class="maincontent">
  Please send any questions or comments to <?php echo "<a href='mailto:".$cfg->get("Owner","email")."'>".$cfg->get("Owner","firstname")." ".$cfg->get("Owner","lastname")."</a>";?>.
  <br />
<?php 

/*
//mobile or not
if($mobile){
    echo "This appears to be a mobile device.";
    }
elseif($_SERVER['REMOTE_ADDR'] == "127.0.0.1"){
    echo "<h1>Looks like you are on the popcornhour.</h1>";
}
else {
    echo "This appears to be a standard browser.";
}
*/
?>
	<div class="block">
	  <h2 id="pageTitle">XBMC</h2>
	  <script type='text/javascript'>
	  $(function() {
		$tabs = $("#tabs").tabs();
		$( ".tabs-bottom .ui-tabs-nav, .tabs-bottom .ui-tabs-nav > *" )
			.removeClass( "ui-corner-all ui-corner-top" )
			.addClass( "ui-corner-bottom" );
		var offset = $("#pageTitle").offset().top;
		//alert("Offset is "+offset);
		$('html,body').animate({scrollTop: offset}, 0);
	  });
	  </script>
	  
	  <div id="tabs">
		<ul>
			<li><a href="#XBMC_navigation">NAV</a></li>
			<li><a href="#XBMC_listing">LIST</a></li>
			<li><a href="#XBMC_nowplaying">PLAY</a></li>
			<li><a href="#XBMC_other">...</a></li>
		</ul>
		<div id="XBMC_navigation">
		  <h3>Database:</h3>
		  <ul class='filelist'>
			  <li class='icon icon_video'><a href='filemanXBMC.php?category=movie&action=viewdatabase#XBMC_listing'>Movies</a>
			  <li class='icon icon_video'><a href='filemanXBMC.php?category=TV&action=viewdatabase#XBMC_listing'>TV</a>
			  <li class='icon icon_audio'><a href='filemanXBMC.php?category=music&action=viewdatabase#XBMC_listing'>Music</a>
		  </ul>
		  <h3>Files:</h3>
		  <ul class='filelist'>
			  <li class='icon icon_audio'><a href='filemanXBMC.php?category=music#XBMC_listing'>Music</a>
			  <li class='icon icon_video'><a href='filemanXBMC.php?category=video#XBMC_listing'>Video</a>
			  <li class='icon icon_photo'><a href='filemanXBMC.php?category=pictures#XBMC_listing'>Pictures</a>
			  <li class='icon icon_folder'><a href='filemanXBMC.php?category=files#XBMC_listing'>Files</a>
		  </ul>
		</div>
		<div id="XBMC_listing">
			<h3>Listing</h3>
			<ul class="filelist">
			<?php
			if($action == "play"){
				//send the request to play the file
				$requestURL = $XBMC_commandURL . urlencode("PlayFile($path)");				
				echo "Requesting $requestURL <br />";
				echo file_get_contents($requestURL);
			}
			else if($action == "download"){
				//send the request to play the file
				$requestURL = $XBMC_commandURL . urlencode("FileDownload($path;'bare')");				
				echo "Requesting $requestURL <br />";
				echo "<pre>";
				echo base64_decode(file_get_contents($requestURL));
				echo "</pre>";
			}
			else if($action == "viewdatabase"){
				//setup the encoding the way we want
				$requestURL = $XBMC_commandURL . urlencode("SetResponseFormat(webheader;false;webfooter;false;closeRecord;</record>;openField; ;closeField;</field>)");
				//Items removed from formatting
				//header; ?xml version='1.0' encoding='UTF-8' ?;
				//openRecordSet;<recordset>;closeRecordSet;</recordset>;
				//openField;<field>;
				//openRecord;<record>;
				
				//echo "setting the record format <a href='$requestURL'>link</a> <br />";
				if(file_get_contents($requestURL) != FALSE){
					if($category == "movie"){
						//setup the sql query
						$sqlQuery = "select c00, strPath, strFilename from movieview ORDER BY c00 ASC";
						//setup the request for the content
						$requestURL = $XBMC_commandURL . urlencode("queryvideodatabase($sqlQuery)");				
					}
					else if($category == "TV"){
						//setup the sql query
						$sqlQuery = "select c00, idShow from tvshow ORDER BY c00 ASC";
						//setup the request for the content
						$requestURL = $XBMC_commandURL . urlencode("queryvideodatabase($sqlQuery)");				
					}
					else if($category == "TVseason"){
						//setup the sql query
						//tvshow: c12 = season, 
						//tvshowlinkepisode
						$sqlQuery = "select distinct c12, idShow from episodeView where idShow = $showid ORDER BY c12 ASC";
						//setup the request for the content
						$requestURL = $XBMC_commandURL . urlencode("queryvideodatabase($sqlQuery)");				
					}
					else if($category == "TVepisode"){
						//select strTitle || " - " c00, strPath, strFileName from episodeview
						//setup the sql query
						$sqlQuery = "select strTitle || ' - ' || c00, strPath, strFileName, c13 from episodeview
										where idShow = $showid and c12 = $season ORDER BY cast(c13 as int) ASC";
						//setup the request for the content
						$requestURL = $XBMC_commandURL . urlencode("queryvideodatabase($sqlQuery)");				
					}
					else if($category == "music"){
						//setup the sql query
						//$sqlQuery = "select idArtist, strArtist from artist"; //shows all artists (including those who didn't lead an album)
						$sqlQuery = "select distinct idArtist, strArtist from albumview ORDER BY strArtist ASC";
						//setup the request for the content
						$requestURL = $XBMC_commandURL . urlencode("querymusicdatabase($sqlQuery)");				
					}
					else if($category == "album"){
						//setup the sql query
						$sqlQuery = "select idAlbum, strAlbum from album where idArtist=$artistid ORDER BY strAlbum ASC";
						//setup the request for the content
						$requestURL = $XBMC_commandURL . urlencode("querymusicdatabase($sqlQuery)");				
					}
					else if($category == "song"){
						//setup the sql query
						$sqlQuery = "select strTitle, strPath || strFileName, iTrack from songview where idArtist=$artistid and idAlbum=$albumid ORDER BY cast(iTrack as int) ASC";
						//setup the request for the content
						$requestURL = $XBMC_commandURL . urlencode("querymusicdatabase($sqlQuery)");				
					}
					//echo "going to fetch <a href='$requestURL'>link</a> <br />";
					//get the full listing
					$listing = file_get_contents($requestURL);
					//break out each of the items by record
					$listing = explode("</record>",$listing);
					array_pop($listing);
					//loop through each record and build out the HTML
					foreach($listing as $item){
						$item = explode("</field>",$item);
						switch($category){
							case "movie":
								echo "<li class='icon icon_video'><a href='filemanXBMC.php?path=$item[1]$item[2]&action=play#XBMC_nowplaying'>$item[0]</a>";
								break;
							case "TV":
								echo "<li class='icon icon_folder'><a href='filemanXBMC.php?category=TVseason&action=viewdatabase&showid=$item[1]#XBMC_listing'>$item[0]</a>";
								break;
							case "TVseason":
								echo "<li class='icon icon_folder'><a href='filemanXBMC.php?category=TVepisode&action=viewdatabase&showid=$item[1]&season=$item[0]#XBMC_listing'>Season $item[0]</a>";
								break;
							case "TVepisode":
								echo "<li class='icon icon_video'><a href='filemanXBMC.php?path=$item[1]$item[2]&action=play#XBMC_nowplaying'>$item[3]. $item[0]</a>";
								break;
							case "music":
								echo "<li class='icon icon_audio'><a href='filemanXBMC.php?category=album&action=viewdatabase&artistid=$item[0]#XBMC_listing'>$item[1]</a>";
								break;
							case "album":
								echo "<li class='icon icon_audio'><a href='filemanXBMC.php?category=song&action=viewdatabase&artistid=$artistid&albumid=$item[0]#XBMC_listing'>$item[1]</a>";
								break;
							case "song":
								echo "<li class='icon icon_audio'><a href='filemanXBMC.php?path=$item[1]&action=play#XBMC_nowplaying'>$item[2]. $item[0]</a>";
								break;
						}
					}
				}
				
				//then change the encoding back
				$requestURL = $XBMC_commandURL . urlencode("SetResponseFormat()");
				file_get_contents($requestURL);
			}		
			else{
			/**********************\
			 *  Basic File View   *
			\**********************/
				if(isset($category)){
						//setup the request URL
						$requestURL = $XBMC_commandURL . urlencode("GetMediaLocation($category;$path)");				
						
						//make the request
						$listing = file_get_contents($requestURL);
						
						//convert it to an array by spliting on <li>
						$listing = explode("<li>",$listing);
						//remove the first item from the array since it will be blank (due to the <li> at the start)
						array_shift($listing);
						//loop through the items and create the HTML
						foreach($listing as $item){
							//break out the individual peices of the item (Label,Path,#)
							//echo "<li>$item<ul>";
							$item = explode(";",$item);
							//if the # is 1 then it's a listable path
							if($item[2] == 1){
								echo "<li class='icon icon_folder'><a href='filemanXBMC.php?category=$category&path=".urlencode($item[1])."#XBMC_listing'>$item[0]</a>";
							}
							else if($item[2] == 0){
								echo "<li class='icon icon_view'><a href='filemanXBMC.php?category=$category&path=".urlencode($item[1])."&action=play#XBMC_nowplaying'>$item[0]<img src='./images/control_play.png'></a>";
								echo " <a href='filemanXBMC.php?category=$category&path=".urlencode($item[1])."&action=download#XBMC_listing'><img src='./images/disk.png'></a>";
							}
							else{
								echo "<li>$item[0]";
							}
							//echo "</ul>";
						}
						//echo file_get_contents($XBMC_commandURL . "GetShares($category)");
						?>
						<script>
						$tabs.tabs('select', 1);
						//$("#XBMC_listing").click();
						</script>
						<?php
				}
				else{
					echo "Select a category or section from the NAV tab to see a listing of the files.";
				}
			}
			?>
			</ul>
		</div>
		<div id="XBMC_other">
			<p>This is the other section.</p>
		</div>
		<div id="XBMC_nowplaying">
		Now Playing:  <br />
		<div class='nowplaying'>
		<?php
		echo "<div id='np_controls'>";
		displayController(null,"filemanXBMC.php?action=remotecontrol","#XBMC_nowplaying");
		if($action == "remotecontrol"){
			switch($command){
				case "play":
					$commandf = "Pause"; //is there a play?
					break;
				case "pause":
					$commandf = "Pause";
					break;
				case "stop":
					$commandf = "Stop";
					break;
				case "rew":
					$commandf = "SetPlaySpeed(-1)";
					break;
				case "fwd":
					$commandf = "SetPlaySpeed(1)";
					break;
				case "next":
					$commandf = "PlayNext";
					break;
				case "prev":
					$commandf = "PlayPrev";
					break;
			}
			$requestURL = $XBMC_commandURL . urlencode($commandf);				
			echo file_get_contents($requestURL);
		}
		echo "</div>";
		
		
		//file_get_contents($XBMC_commandURL . getcurrentlyplaying);
		$tmp = file_get_contents($XBMC_commandURL . getcurrentlyplaying);
		//echo "<pre>$tmp</pre>";
		$tmp = explode("<li>",$tmp);
		foreach($tmp as $key => $val){ 
			$val = explode(":",$val,2);
			$nowplaying[$val[0]] = trim($val[1]);
		}
		//clear out the temporary array
		unset($tmp);
		
		if(isset($nowplaying['Type'])){
			//setup the now playing section
			if($nowplaying['Type'] == 'Video'){
				echo "<div class='icon icon_video' style='padding-left:20px;background-position:0% 50%;height:20px;display:inline;'></div>";
			}
			
			//setup the headline info
			echo "<div>";
			echo "<span id='np_title'>".$nowplaying['Title'] . "</span> (<span id='np_time'>".$nowplaying['Time']."</span>) <span id='np_percentage'>".$nowplaying['Percentage']."</span>%";
			echo "</div>";
		}
		
		//try to create the thumb
		//FileDownload()
		//$nowplaying['Thumb'];
		echo "<br />";
		
		if(isset($nowplaying['Plot'])){
			//setup the plot
			echo "<div>";
			echo "Plot: <span id='np_plot'>".$nowplaying['Plot']."</span>";
			echo "</div>";
		}
		//closing div for the nowplaying class
		echo "</div>";
		?>
		</div>
	</div>

</div>
</BODY>